package com.yunji.hushuang;

import java.io.*;

/**
 * 枚举类单例(注册式单例的一种)
 *
 * @author hushuang
 * @since 2019/9/29
 */
public enum EnumSingleton {

    /**
     *
     */
    INSTANCE;

    public static EnumSingleton getInstance() {
        return INSTANCE;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    private Object data;

    public static void main(String[] args) {
        testDeserializationBroken();
        testReflectBroken();
    }

    private static void testDeserializationBroken() {
        EnumSingleton instance1 = EnumSingleton.getInstance();
        EnumSingleton instance2 = null;
        instance1.setData(new Object());

        try (FileOutputStream fileOutputStream = new FileOutputStream("EnumSingleton.obj");
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
            objectOutputStream.writeObject(instance1);
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (FileInputStream fileInputStream = new FileInputStream("EnumSingleton.obj");
             ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            instance2 = (EnumSingleton) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(instance1.getData());
        System.out.println(instance2.getData());
        System.out.println(instance1.getData() == instance2.getData());
    }

    private static void testReflectBroken() {
        EnumSingleton instance1 = EnumSingleton.getInstance();
        instance1.setData(new Object());

        try {
            EnumSingleton.class.getDeclaredConstructor(String.class, int.class).newInstance("INSTANCE", 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
